<?php

$__FILEPATH__ = dirname(__FILE__)."/";
require_once($__FILEPATH__."./func_common.php");
require_once($__FILEPATH__."./class_def.php");
require_once($__FILEPATH__."./conf/info.php");
header("Content-Type: text/html; charset=UTF-8");

if(isset($_POST["reg"]))
{
	unset($_SESSION["admin"]);
	unset($_SESSION["user"]);

	$strsql = "insert into userlist(username,password,nickname,sex,school,email,imagesrc,intra,ip,rgtime,permission) ";
	$strsql = $strsql."values(?,?,?,?,?,?,?,?,?,?,'user')";

	$username 	= $_POST["username"];
	$password 	= $_POST["password"];
	$confirm 	= $_POST["confirm"];
	$nickname 	= $_POST["nickname"];
	$sex 		= $_POST["sex"];
	$school 	= $_POST["school"];
	$imagename 	= $_FILES['imagefile']["name"];
	$email 		= $_POST["email"];
	$ip 		= GetRequestIP();
	$rgtime 	= GetSysTime();
	$intra 		= $_POST["intra"];

	if ($imagename != "")
		$imagesrc = GetFormalImgPath($imagename);
	else 
		$imagesrc = "none";

	if(Check($username, $nickname, $password, $confirm, $sex, $school, $intra)
		&& ($imagename == "" || JudgeUpLoadImageFile($_FILES['imagefile'])))
	{
		if ($_POST["email"] != "" && !IsValidEmail($_POST["email"]) )
			echo "<script type='text/javascript'>alert('电子邮件格式非法');</script>";
		else
		{
			$password = md5($password);
			$mysqli = GetMysqliInstance();
			$stmt = $mysqli->prepare($strsql);
			$stmt->bind_param("ssssssssss", $username, $password, $nickname, $sex, $school, $email, $imagesrc, $intra, $ip, $rgtime);
			if($stmt->execute()) 
			{
				if ($imagename != "")
					UploadImage($_FILES['imagefile'], $imagesrc);

				ClientRedirect("./loginpage.php", "恭喜！注册账号成功, 请登录！");
			}
			else
				die("<h4 style='color:red'>注册失败，可能账号已经存在~</h4>");

			$stmt->close();
			$mysqli->close();
		}
	}
	else 
		die("<h4 style='color:red'>注册失败，请按要求填写~<h4>");
}

function Check($username,$nickname,$password,$confirm,$sex,$school,$intra)
{
	if( $sex == ""
		|| $username == "" 
		|| $nickname == "" 
		|| $password == ""
		|| !CheckStrInNumAndChar($username)
		|| !CheckStrInNumAndChar($password)
		|| !CheckStrInNumAndChar($confirm)
		|| $password != $confirm
		|| strlen($sex) > 8
		|| strlen($username) > 64
		|| strlen($nickname) > 64
		|| strlen($school) > 128
		|| strlen(intra) > 10000
		)
		return false;
	return true;
}


?>